from PyQt5.QtWidgets import QLabel, QHBoxLayout
from PyQt5.Qsci import QsciScintilla, QsciLexerPython, QsciLexerCPP, QsciLexerMarkdown, QsciLexerHTML, QsciLexerSQL
from pmgwidgets.widgets.extended.base.baseextendedwidget import BaseExtendedWidget

# 定义lexer的映射表
lexers = {'python': QsciLexerPython,
          'cpp': QsciLexerCPP,
          'html': QsciLexerHTML,
          'markdown': QsciLexerMarkdown,
          'sql': QsciLexerSQL
          }


class PMGEditorCtrl(BaseExtendedWidget):
    def __init__(self, layout_dir: str, title: str, initial_value: str = '', lexer_name=''):
        super().__init__(layout_dir)
        self.on_check_callback = None

        self.prefix = QLabel(text=title)

        entryLayout = QHBoxLayout()
        entryLayout.setContentsMargins(0, 0, 0, 0)
        self.ctrl = QsciScintilla()
        lexer_class = lexers.get(lexer_name)
        if lexer_class is not None:
            self.ctrl.setLexer(lexer_class())
        
        self.ctrl.setAnnotationDisplay(QsciScintilla.AnnotationBoxed)  # 提示显示方式
        self.ctrl.setAutoCompletionSource(QsciScintilla.AcsAll)  # 自动补全。对于所有Ascii字符
        self.ctrl.setAutoCompletionReplaceWord(True)
        self.ctrl.setAutoCompletionCaseSensitivity(False)  # 忽略大小写
        self.ctrl.setAutoCompletionThreshold(1)  # 输入多少个字符才弹出补全提示
        self.ctrl.setAutoCompletionUseSingle(QsciScintilla.AcusNever)
        self.ctrl.setText(initial_value)

        self.central_layout.addWidget(self.prefix)
        self.central_layout.addLayout(entryLayout)
        entryLayout.addWidget(self.ctrl)
        self.set_value(initial_value)

    def get_value(self):
        return self.ctrl.text()

    def set_value(self, value: str):
        self.ctrl.setText(value)
